(function() {
    'use strict';
    angular.module('services.workOrderData', [
            'services.workOrderData.indexMgmt',
            'services.workOrderData.eventMgmt',
            'services.workOrderData.problemMgmt',
            'services.workOrderData.publishMgmt',
            'services.workOrderData.useAndHandle',
            'services.workOrderData.developWorks',
            'services.workOrderData.auditData'
        ])
        .service('workOrderDataService', workOrderDataService);

    function workOrderDataService(Restangular, CoreService) {
        return {
            queryMeasureIndex: queryMeasureIndex,
            queryStatisticType: queryStatisticType,
            getSendData: getSendData,
            fmtSendData: fmtSendData,
            getEchartsData: getEchartsData,
            getEchartsPieData: getEchartsPieData,
            getName: getName,
            getArrayData: getArrayData,
            getEchartsLineData: getEchartsLineData,
            exportView: exportView,
            queryNoDataOrError: queryNoDataOrError,
            getFormatterFn: getFormatterFn,
            formatterYAxis: formatterYAxis
        };
        //查询衡量指标
        function queryMeasureIndex(params, callback) {
            Restangular.all('sas/common/queryMeasureIndex').post(params).then(callback);
        }
        //查询统计维度
        function queryStatisticType(params, callback) {
            Restangular.all('sas/common/queryStatisticsType').post(params).then(callback);
        }
        //页面绑定对象初始值
        function getSendData(timeType) {
            var year = new Date().getFullYear();
            var month = new Date().getMonth();
            var startTime, endTime;
            switch (timeType) {
                case '3':
                    startTime = new Date(year, month - 6);
                    endTime = new Date(year, month - 1);
                    break;
                default:
                    startTime = new Date(year, month - 1, 1);
                    endTime = new Date(year, month, 0);
                    break;
            }
            return {
                startTime: startTime,
                endTime: endTime,
                measureIndexCode: '1',
                changeTypeCode: '',
                timeType: timeType
            };
        }
        //格式化需求发送给后端的字段
        function fmtSendData(sendData) {
            var send = {
                startTime: '',
                endTime: '',
                measureIndexCode: '',
                timeType: ''
            };
            send.startTime = CoreService.dateFormat(sendData.startTime, 'yyyy-MM-dd');
            send.endTime = CoreService.dateFormat(sendData.endTime, 'yyyy-MM-dd');
            send.measureIndexCode = sendData.measureIndexCode;
            send.changeTypeCode = sendData.changeTypeCode;
            send.timeType = sendData.timeType;
            return send;
        }
        //柱状图
        function getEchartsData(xAxisData, seriesData, title, legendName) {
            return {
                title: {
                    text: title,
                    x: 'center'
                },
                animation: false,
                tooltip: {
                    trigger: 'item'
                },
                grid: {
                    x2: 100
                },
                legend: {
                    data: [legendName],
                    orient: 'vertical',
                    x: 'right',
                    y: 'center'
                },
                xAxis: [{
                    type: 'category',
                    data: xAxisData
                }],
                yAxis: [{
                    type: 'value'
                }],
                series: [{
                    name: legendName,
                    type: 'bar',
                    data: seriesData
                }]
            };
        }
        //饼图
        function getEchartsPieData(items, title) {
            var seriesData = [];
            angular.forEach(items, function(item) {

                seriesData.push({
                    value: Number(item.percentage.substring(0, item.percentage.length - 1)).toFixed(2),
                    name: item.filedName
                });
            });
            var option = {
                title: {
                    text: title,
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{b} :{d}%'
                },
                animation: false,
                series: [{
                    type: 'pie',
                    radius: '70%',
                    center: ['50%', '60%'],
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                formatter: function(param) {
                                    return param.name + '\n' + param.percent + '%';
                                }
                            }
                        }
                    },
                    data: seriesData
                }]
            };
            return option;
        }
        //获取页面表头信息和echarts图x轴数据
        function getArrayData(data) {
            var array = {
                xData: [],
                tableTh: []
            };
            angular.forEach(data, function(d) {
                if (array.xData.indexOf(d.time) === -1) {
                    array.xData.push(d.time);
                }
                angular.forEach(d.lineData, function(item) {
                    if (array.tableTh.indexOf(item.filedName) === -1) {
                        array.tableTh.push(item.filedName);
                    }
                });
            });
            return array;
        }
        //拆线图
        function getEchartsLineData(items, resource, title, countName) {
            var temp = {
                xData: items.xData,
                legendName: items.tableTh,
                seriesData: [],
            };
            var obj = {};
            angular.forEach(resource, function(res) {
                angular.forEach(res.lineData, function(ld) {
                    var fne = ld[countName].substr(ld[countName].length-1);
                    if(fne === '%'){
                        if (!obj[ld.filedName]) {
                        obj[ld.filedName] = [Number(ld[countName].replace('%', '')).toFixed(2)];
                    } else {
                        obj[ld.filedName].push(Number(ld[countName].replace('%', '')).toFixed(2));
                    }
                }else{
                    if (!obj[ld.filedName]) {
                        obj[ld.filedName] = [Number(ld[countName].replace('%', ''))];
                    } else {
                        obj[ld.filedName].push(Number(ld[countName].replace('%', '')));
                    }
                }
                });
            });

            angular.forEach(temp.legendName, function(ln, index) {
                temp.seriesData[index] = {
                    name: ln,
                    type: 'line',
                    data: obj[ln]
                };
            });
            return getOption(temp, title);
        }
        //折线图option实例
        function getOption(temp, echartstitle) {
            return {
                title: {
                    text: echartstitle,
                    x: 'center'
                },
                animation: false,
                tooltip: {
                    show: true
                },
                grid: {
                    x2: 130
                },
                legend: {
                    data: temp.legendName,
                    orient: 'vertical',
                    x: 'right',
                    y: 'center'
                },
                xAxis: [{
                    type: 'category',
                    data: temp.xData
                }],
                yAxis: [{
                    type: 'value'
                }],
                series: temp.seriesData
            };
        }
        //根据衡量指标code获取所对应的名字
        function getName(code, measureIndexs, measureIndexCode, measureIndexName) {
            var name = '';
            if (code) {
                angular.forEach(measureIndexs, function(res) {
                    if (res[measureIndexCode] === code) {
                        name = res[measureIndexName];
                    }
                });
            }
            return name;
        }
        //导出
        function exportView(myEcharts, send) {
            send.base64 = [];
            var b = myEcharts.getDataURL('png');
            send.base64.push(b.split(',')[1]);
            return JSON.stringify(send);
        }

        function queryNoDataOrError(flag, message) {
            flag.state = true;
            flag.arrow = false;
            flag.show = '';
            CoreService.dialog(message);
        }

        function getFormatterFn(str) {
            return function(params) {
                var name = params.name;
                var seriesName = params.seriesName;
                var value = params.value;
                return seriesName + ' </br>' + name + ':' + value + str;
            };
        }

        function formatterYAxis(yName, yFormatter) {
            return {
                name: yName,
                axisLabel: {
                    formatter: yFormatter
                }
            };
        }
    }
})();
